<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_comm_summary($in_date){
/*
This function calculates the bonus summary for all the members and store the result to the database.
*/

	global $vars;
	$db=$vars["db"];
	$comm_time = strtotime($in_date);
	$month = date('n', $comm_time);
	$year = date('Y', $comm_time);
	$calc_date['start'] = date('Y-m-d H:i:s', mktime(0,0,0,$month,1,$year));
	$calc_date['end'] = date('Y-m-d H:i:s', mktime(23,59,59,$month+1,0,$year));
	$comm_title = "Bonus Summary Calculation";
	
	//get all the members that is not terminated
	$prev_uid = 0;
	$t = @mysql_num_rows($r=mysql_query("select uid, type, sum(amount) as amount, sum(amount2) as amount2 from $db->member_comm where year='$year' and month='$month' and status='confirmed' group by uid, type order by uid"));
	for($i=0;$i<$t;$i++){
		$comm = mysql_fetch_assoc($r);
		$uid = $comm['uid'];
		if($uid != $prev_uid && $i != 0){
			foreach($comms as $code => $amount){
				$cqf .= "c$code, ";
				$cqv .= "'$amount', ";
			}
			$cqf = rtrim($cqf, ', ');
			$cqv = rtrim($cqv, ', ');
			$sql = "insert into $db->member_comm_sum (uid, $cqf, year, month) values ('$prev_uid', $cqv, '$year', '$month')";
			if(!mysql_query($sql)){
				$insert_err .= "$sql\n";
			}
			unset($comms, $cqf, $cqv);
		}
		if($comm['type'] == 'm'){
			$comms[$comm['type'].'1'] = $comm['amount'];
			$comms[$comm['type'].'2'] = $comm['amount2'];
		}else{
			$comms[$comm['type']] = $comm['amount'];
		}
		$prev_uid = $uid;
	}
	//last user
	if($comms){
		foreach($comms as $code => $amount){
			$cqf .= "c$code, ";
			$cqv .= "'$amount', ";
		}
		$cqf = rtrim($cqf, ', ');
		$cqv = rtrim($cqv, ', ');
		$sql = "insert into $db->member_comm_sum (uid, $cqf, year, month) values ('$uid', $cqv, '$year', '$month')";
		if(!mysql_query($sql)){
			$insert_err .= "$sql\n";
		}
		unset($comms, $cqf, $cqv);
	}
	
	if($insert_err){
		$errmsg = ($insert_err? "$comm_title calculation error:\n\n$insert_err\n" : "");
		$status = false;
	}else{
		$status = true;
	}
	$result['status'] = $status;
	$result['errmsg'] = $errmsg;
	
	return $result;
}
?>